export default class SocketService {
  /**
   * 单例模式
   */
  static instance = null;
  // 业务类型和回调函数的对于关系
  callBackMapping = {}
  //是否连接成功
  connected =false
  //尝试发送 奇数 下一次再发起重连的延时也就越长
  sendRetryCiunt = 0
// 重连次数, 重连次数越大, 下一次再发起重连的延时也就越长
  connectRetryCount = 0 
  
  static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService()
    }
    return this.instance
  }
  //实例属性
  ws = null
  //初始化连接 websocket
  connect() {
    if (!window.WebSocket) {
      return console.log("你的电脑浏览器不支持 websocket");
    }
    this.ws = new WebSocket('ws://localhost:9999')

    this.ws.onopen = () => {
      console.log('连接成功')
      this.connected =true
      this.connectRetryCount = 0 // 连接成功之后, 重置重连次数
    }

    this.ws.onclose = e => {
      console.log('服务器关闭了连接')
      this.connected=false
      this.connectRetryCount++
      setTimeout(() => {
        this.connect()
      }, 200*this.connectRetryCount);
    }

    this.ws.onmessage = msg => {
      console.log('WebSocket 接收到数据')
      console.log(JSON.parse(msg.data))
      const recvData = JSON.parse(msg.data)//取出服务器传递的数据
      const socketType = recvData.socketType //取出业务类型，要求据业务类型，得到回调函数
      //先判断 有没有回调函数
      if(this.callBackMapping[socketType]){
        if(recvData.action === 'getData'){
          const realData =recvData.data //得到该图标数据
          this.callBackMapping[socketType].call(this,JSON.parse(realData))
        } else if (recvData.action === 'fullScreen') {
          this.callBackMapping[socketType].call(this, msg)
        } else if (recvData.action === 'themeChange') {
          this.callBackMapping[socketType].call(this, msg)
        }
      }
    }
  }
     
  registerCallBack(socketType, callBack){
     // 往 callBackMap中存放回调函数
    this.callBackMapping[socketType] = callBack
  }

  unRegisterCallBack(socketType){
    this.callBackMapping[socketType] = null
  }

  send(data){
    console.log("发送给服务器的数据")
    if(this.connected){
      this.sendRetryCiunt=0
      this.ws.send(JSON.stringify(data))
    }else{
      setTimeout(() => {
        this.sendRetryCiunt++
        this.send(data)
      }, 500);// 发送数据尝试的次数越大, 则下一次连接的延迟也就越长
    }
  }

  a(){
    console.log("沙发哈哈福建")
  }
  
}
